// components/product-scale-item/index.js
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { formatPrice } from '../../../common/utils';
import { tipToast } from '../../../common/env';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        current: {
            type: Number,
            optionalTypes: [String],
            value: 0,
        },
        length: {
            type: Number,
            optionalTypes: [String],
            value: 0,
        },
        scaleInfo: {
            type: Object,
            value: {},
        },
        scaleInfoCache: {
            type: Object,
            value: {},
        },
        canModify: {
            type: Boolean,
            value: true,
        },
        canModifyPrice: {
            type: Boolean,
            value: true,
        },
    },
    observers: {
        'scaleInfo': function (scaleInfo) {
            if (scaleInfo) {
                scaleInfo.maximum = scaleInfo.maximum <= 0 ? '' : scaleInfo.maximum;
                const price = formatPrice(scaleInfo.price, true);
                this.setData({ price, skuInfo: scaleInfo });
            }
        },
    },
    data: {
        skuInfo: {},
        price: '',
    },
    methods: {
        handleChangePrice(e) {
            if (!this.data.canModify) {
                return;
            }
            const { productSpecId, maximum } = this.data.skuInfo;
            const price = formatPrice(e.detail.value);
            this.triggerEvent('change', {
                productSpecId,
                price,
                maximum,
            });
        },
        handleChangeMaximum(e) {
            const { scaleInfoCache } = this.data;
            const { productSpecId, price } = this.data.skuInfo;
            let maximum = e.detail;
            if (!this.data.canModify && maximum !== '' && scaleInfoCache && maximum < scaleInfoCache.maximum) {
                tipToast(`库存不能小于${scaleInfoCache.maximum}`);
                maximum = scaleInfoCache.maximum;
            }
            this.triggerEvent('change', {
                productSpecId,
                price,
                maximum,
            });
        },
    }
})
